from threading import Thread

COMMAND_FORMAT = "!16sI"

class LeechWorker(Thread):
    def __init__(self, sock, chunk_idx, brook, network):
        super(LeechWorker, self).__init__()
        self._conn = sock
        self.chunk_idx = chunk_idx
        self._brook = brook
        self._network = network
        self.done = False
        if self._brook.number_of_chunks == chunk_idx:
            self._size_of_data = self._brook.last_chunk_size
        else:
            self._size_of_data = self._brook.chunk_size

    def run(self):
        print "Recieving chunck ", self.chunk_idx, " from: ", self._conn.getpeername()
        try:
            data = self.recieve()
            if self._brook.verify_chunk(self.chunk_idx, data):
                with self._brook.object_lock:
                    self._brook.write_chunk(self.chunk_idx, data)
                    self._network._chunk_rarity[self.chunk_idx] = None
            else:
                print "bad data!!!"
        except Exception:
            print "Something went wrong while leeching: "
            raise
        finally:
            self.done = True
    
    def recieve(self):
        data = ""
        while len(data) < self._size_of_data:
            data = data + self._conn.recv(4096)
        return data